package models.weixin;

import models.BaseModel;
import models.admin.AdminUser;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import play.db.jpa.JPA;
import util.common.DateUtil;
import util.common.UStringUtil;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

/**
 * created by weiwei on 2018-02-22
 * 为划分的用户分类添加用户
 */
@Entity
@Table(name="web_user_classify_items")
public class WebUserClassifyItem extends BaseModel {

    /**
     * 用户分类
     */
    @JoinColumn(name = "web_user_classify_id")
    @ManyToOne
    public WebUserClassify webUserClassify;



    /**
     * 微信用户名称
     */
    @JoinColumn(name = "web_user_id")
    @ManyToOne
    public WebUser webUser;


    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;


    /**
     * 检查分类下是否有webUser
     * @param webUserClassifyId
     * @return
     */
    public static Boolean checkItems(long webUserClassifyId){
        return WebUserClassifyItem.count(" webUserClassify.id = ? and deleted = ?" , webUserClassifyId , DeletedStatus.UN_DELETED) > 0;
    }

    /**
     * 查询分类下的webUser
     * @param webUserClassifyId
     * @return
     */
    public static List<WebUserClassifyItem> loadByWebUserClassifyId(long webUserClassifyId){
        return WebUserClassifyItem.find(" webUserClassify.id = ? and deleted = ?" , webUserClassifyId , DeletedStatus.UN_DELETED).fetch();
    }





    /**
     * 删除
     * @param delIds
     * @param loginUser
     */
    public static void deletedByIds(Long[] delIds , AdminUser loginUser){
        String ids = UStringUtil.concatStr(",",delIds);

        String sqlUpdate = " update web_user_classify_items a set a.deleted = 1 ,a.modifier_id = "+loginUser.id+" , a.modify_at = '"+ DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")+"' where a.id in ("+ids+")";

        JPA.em().createNativeQuery(sqlUpdate).executeUpdate();
    }


    /**
     * 查询用户划分的类，并按照使用优先级别高的分类
     * @param user
     * @param merchant
     * @return
     */
    public static WebUserClassifyItem findByUserAndMerchant(WebUser user , Merchant merchant){
        return WebUserClassifyItem.find("webUser = ? and webUserClassify.merchant = ? and deleted = ? order by webUserClassify.level asc " , user , merchant , DeletedStatus.UN_DELETED).first();
    }

}
